'use strict';

const db = uniCloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  console.log('【getRecommendMessages】云函数被调用，event：', event);
  
  const { userId, limit = 10 } = event;
  
  if (!userId) {
    return {
      code: 400,
      msg: '用户ID缺失',
      data: []
    };
  }
  
  try {
    // 先尝试从数据库获取已存储的推荐消息
    const recommendCollection = db.collection('recommendMessages');
    const existingMessages = await recommendCollection
      .where({
        user_id: userId,
        status: 'active'
      })
      .orderBy('create_time', 'desc')
      .limit(limit)
      .get();
    
    // 如果存在未过期的推荐消息（24小时内），直接返回
    const now = Date.now();
    const validMessages = existingMessages.data.filter(msg => 
      (now - msg.create_time) < 24 * 60 * 60 * 1000 // 24小时内
    );
    
    if (validMessages.length > 0) {
      console.log('【返回已存储的推荐消息】', validMessages.length, '条');
      return {
        code: 200,
        msg: '获取推荐消息成功',
        data: validMessages
      };
    }
    
    console.log('【生成新的推荐消息】');
    
    // 获取用户基础信息
    let user = { credit_score: 0, region: '' };
    const userInfo = await db.collection('user')
      .where({ _id: userId })
      .field({ credit_score: 1, region: 1 })
      .get();
      
    if (userInfo.data.length > 0) {
      user = { ...user, ...userInfo.data[0] };
    }
    console.log('【用户信息】', user);

    const recommendMessages = [];
    
    // 1. 个性化任务推荐
    const personalizedTasks = await getPersonalizedTaskRecommendations(userId, user);
    recommendMessages.push(...personalizedTasks);
    console.log('【个性化推荐数量】', personalizedTasks.length);
    
    // 2. 热门任务推荐
    const hotTasks = await getHotTaskRecommendations(userId, user);
    recommendMessages.push(...hotTasks);
    console.log('【热门推荐数量】', hotTasks.length);
    
    // 3. 系统活动推荐
    const systemActivities = await getSystemActivityRecommendations(userId);
    recommendMessages.push(...systemActivities);
    console.log('【活动推荐数量】', systemActivities.length);
    
    // 4. 兜底推荐（如果任务推荐为空，补充任务推荐）
    const taskRecommendCount = recommendMessages.filter(msg => 
      msg.type === 'task' || msg.type === 'personalized' || msg.type === 'hot'
    ).length;
    
    if (taskRecommendCount === 0) {
      console.log('【触发兜底推荐】没有任务推荐，补充任务推荐');
      const fallbackTasks = await getFallbackRecommendations(userId);
      recommendMessages.push(...fallbackTasks);
    }
    
    // 5. 如果仍然为空，提供基础推荐
    if (recommendMessages.length === 0) {
      console.log('【触发最终兜底推荐】所有推荐源为空');
      recommendMessages.push({
        _id: 'final_fallback',
        user_id: userId,
        type: 'system',
        title: '欢迎使用',
        content: '欢迎使用校园互助平台，快来发布或接取任务吧！',
        reason: '系统推荐',
        score: 0.1,
        is_read: false,
        createTime: new Date(),
        status: 'active'
      });
    }
    
    // 排序和限制数量
    const sortedMessages = recommendMessages
      .sort((a, b) => (b.score || 0) - (a.score || 0))
      .slice(0, limit);
    
    console.log('【最终推荐数量】', sortedMessages.length);
    
    // 存储推荐消息到数据库
    if (sortedMessages.length > 0) {
      try {
        // 先删除该用户的旧推荐消息（避免重复）
        await recommendCollection.where({
          user_id: userId,
          status: 'active'
        }).remove();
        
        // 批量插入新的推荐消息
        const messagesToInsert = sortedMessages.map(msg => ({
          ...msg,
          create_time: Date.now(), // 使用Unix时间戳
          status: 'active',
          avatar: '/static/images/default-avatar.png' // 添加默认头像
        }));
        
        await recommendCollection.add(messagesToInsert);
        console.log('【推荐消息存储成功】', messagesToInsert.length, '条');
      } catch (storageError) {
        console.error('【推荐消息存储失败】', storageError);
        // 存储失败不影响返回结果
      }
    }
    
    return {
      code: 200,
      msg: '获取推荐消息成功',
      data: sortedMessages
    };
    
  } catch (error) {
    console.error('【getRecommendMessages】异常:', error);
    // 异常时返回基础推荐
    const fallbackTasks = await getFallbackRecommendations(event.userId);
    return {
      code: 500,
      msg: '获取推荐消息失败：' + error.message,
      data: fallbackTasks.slice(0, 5) // 增加返回数量
    };
  }
};

// 1. 个性化任务推荐
async function getPersonalizedTaskRecommendations(userId, user) {
  try {
    const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
    const userTasks = await db.collection('taskList')
      .where(_.or([
        { publisher_id: userId },
        { receiver_id: userId, status: 'completed' }
      ]))
      .where({ publish_time: _.gte(thirtyDaysAgo) })
      .get();
    
    // 如果用户无历史数据，返回空
    if (userTasks.data.length === 0) {
      console.log('【个性化推荐】用户无历史任务数据，跳过个性化推荐');
      return [];
    }
    
    console.log('【个性化推荐】用户历史任务数量:', userTasks.data.length);
    
    const preferences = analyzeUserPreferences(userTasks.data);
    
    // 查询推荐任务（放宽条件）
    const recommendedTasks = await db.collection('taskList')
      .where({
        status: 'pending',
        publisher_id: _.neq(userId)
        // 移除时间限制和信用分限制，与兜底推荐保持一致
      })
      .limit(10)
      .get();
    
    const validTasks = recommendedTasks.data.filter(task => task.status === 'pending');
    
    console.log('【个性化推荐】查询到的任务数量:', recommendedTasks.data.length);
    console.log('【个性化推荐】有效任务数量:', validTasks.length);
    
    return validTasks
      .map(task => ({
        _id: `personalized_${task._id}`,
        user_id: userId,
        type: 'personalized',
        title: '个性化任务推荐',
        content: `根据您的兴趣，推荐"${task.title}"（${task.type}，${task.reward}元）`,
        task_id: task._id,
        reason: `基于您对${preferences.preferredType}类型任务的偏好`,
        score: calculateTaskMatchScore(task, preferences),
        is_read: false,
        createTime: new Date(),
        status: 'active'
      }))
      .filter(item => item.score > 0.2)
      .slice(0, 3);
    
  } catch (error) {
    console.error('【个性化推荐异常】', error);
    return [];
  }
}

// 2. 热门任务推荐
async function getHotTaskRecommendations(userId, user) {
  try {
    const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
    
    const hotTasks = await db.collection('taskList')
      .where({
        status: 'pending',
        publisher_id: _.neq(userId)
        // 移除时间限制和信用分限制，与兜底推荐保持一致
      })
      .orderBy('publish_time', 'desc')
      .limit(10)
      .get();
    
    console.log('【热门推荐】查询到的任务数量:', hotTasks.data.length);
    
    const validHotTasks = hotTasks.data.filter(task => task.status === 'pending');
    console.log('【热门推荐】有效任务数量:', validHotTasks.length);
    
    return validHotTasks
      .map(task => ({
        _id: `hot_${task._id}`,
        user_id: userId,
        type: 'hot',
        title: '热门任务推荐',
        content: `热门任务"${task.title}"（${task.reward}元，${task.type}）`,
        task_id: task._id,
        reason: '近期发布的热门任务',
        score: calculateHotScore(task),
        is_read: false,
        createTime: new Date(),
        status: 'active'
      }))
      .slice(0, 4);
    
  } catch (error) {
    console.error('【热门推荐异常】', error);
    return [];
  }
}

// 3. 系统活动推荐
async function getSystemActivityRecommendations(userId) {
  try {
    const activityRecommendations = [
      {
        _id: 'system_base_1',
        user_id: userId,
        type: 'activity',
        title: '任务推荐',
        content: '查看更多任务，完成任务可获得积分奖励',
        activity_id: 'base_activity',
        reason: '系统推荐',
        score: 0.5,
        is_read: false,
        createTime: new Date(),
        status: 'active'
      },
      {
        _id: 'system_base_2',
        user_id: userId,
        type: 'activity',
        title: '积分奖励',
        content: '完成任务可获得积分，积分可用于兑换礼品',
        activity_id: 'points_activity',
        reason: '积分系统',
        score: 0.6,
        is_read: false,
        createTime: new Date(),
        status: 'active'
      },
      {
        _id: 'system_base_3',
        user_id: userId,
        type: 'activity',
        title: '信用提升',
        content: '完成更多任务可提升信用等级，享受更多特权',
        activity_id: 'credit_activity',
        reason: '信用系统',
        score: 0.7,
        is_read: false,
        createTime: new Date(),
        status: 'active'
      }
    ];
    
    // 额外活动逻辑
    const userTasks = await db.collection('taskList')
      .where(_.or([
        { publisher_id: userId },
        { receiver_id: userId, status: 'completed' }
      ]))
      .get();
    
    const completedTasks = userTasks.data.filter(task => 
      task.receiver_id === userId && task.status === 'completed'
    ).length;
    
    if (completedTasks < 3) {
      activityRecommendations.push({
        _id: 'system_activity_1',
        user_id: userId,
        type: 'activity',
        title: '新手福利',
        content: '完成前3个任务可获得额外50积分奖励！',
        activity_id: 'activity_1',
        reason: '新手专属',
        score: 0.9,
        is_read: false,
        createTime: new Date(),
        status: 'active'
      });
    }
    
    return activityRecommendations;
    
  } catch (error) {
    console.error('【活动推荐异常】', error);
    return [{
      _id: 'fallback_activity',
      user_id: userId,
      type: 'activity',
      title: '任务广场',
      content: '点击查看更多任务',
      activity_id: 'fallback',
      score: 0.5,
      is_read: false,
      createTime: new Date()
    }];
  }
}

// 4. 兜底推荐
async function getFallbackRecommendations(userId) {
  try {
    console.log('【兜底推荐】生成基础推荐');
    
    const fallbackTasks = await db.collection('taskList')
      .where({
        status: 'pending',
        publisher_id: _.neq(userId)
      })
      .limit(5)
      .get();
    
    console.log('【兜底推荐】查询到的任务数量:', fallbackTasks.data.length);
    
    const taskRecommendations = fallbackTasks.data.map(task => ({
      _id: `fallback_${task._id}`,
      user_id: userId,
      type: 'task',
      title: '任务推荐',
      content: `"${task.title}"（${task.reward}元，${task.type}）`,
      task_id: task._id,
      reason: '为您推荐可接任务',
      score: 0.3,
      is_read: false,
      createTime: new Date()
    }));
    
    if (taskRecommendations.length === 0) {
      return [
        {
          _id: 'ultimate_fallback_1',
          user_id: userId,
          type: 'system',
          title: '发现任务',
          content: '暂无推荐任务，去任务广场看看吧',
          reason: '系统推荐',
          score: 0.1,
          is_read: false,
          createTime: new Date()
        },
        {
          _id: 'ultimate_fallback_2',
          user_id: userId,
          type: 'system',
          title: '新手引导',
          content: '欢迎使用校园互助平台，快来发布或接取任务吧！',
          reason: '新手推荐',
          score: 0.2,
          is_read: false,
          createTime: new Date()
        },
        {
          _id: 'ultimate_fallback_3',
          user_id: userId,
          type: 'system',
          title: '功能探索',
          content: '探索更多功能：发布任务、接取任务、积分兑换等',
          reason: '功能推荐',
          score: 0.15,
          is_read: false,
          createTime: new Date()
        }
      ];
    }
    
    return taskRecommendations;
    
  } catch (error) {
    console.error('【兜底推荐异常】', error);
    return [
      {
        _id: 'error_fallback_1',
        user_id: userId,
        type: 'system',
        title: '提示',
        content: '点击刷新推荐任务',
        score: 0.1,
        is_read: false,
        createTime: new Date()
      },
      {
        _id: 'error_fallback_2',
        user_id: userId,
        type: 'system',
        title: '系统维护',
        content: '推荐系统正在维护中，请稍后再试',
        score: 0.05,
        is_read: false,
        createTime: new Date()
      }
    ];
  }
}

// 辅助函数
function analyzeUserPreferences(userTasks) {
  const typeCount = {};
  userTasks.forEach(task => {
    const taskType = task.type || 'other';
    typeCount[taskType] = (typeCount[taskType] || 0) + 1;
  });
  const preferredType = Object.keys(typeCount).reduce((a, b) => 
    typeCount[a] > typeCount[b] ? a : b, 'other');
  return { preferredType, typeDistribution: typeCount };
}

function calculateTaskMatchScore(task, preferences) {
  let score = 0.2;
  if (task.type === preferences.preferredType) score += 0.4;
  if (task.reward >= 5) score += 0.2;
  const hoursDiff = (new Date() - new Date(task.publish_time)) / (1000 * 60 * 60);
  if (hoursDiff < 48) score += 0.2;
  return Math.min(score, 1.0);
}

function calculateHotScore(task) {
  let score = 0.2;
  score += Math.min(task.reward / 50, 0.3);
  const hoursDiff = (new Date() - new Date(task.publish_time)) / (1000 * 60 * 60);
  if (hoursDiff < 72) score += 0.3;
  return Math.min(score, 1.0);
}